package com.wanxi.servlet;

import java.io.*;
import java.util.List;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.alibaba.fastjson2.JSONObject;
import com.wanxi.dto.ImgDTO;
import com.wanxi.dto.ResultDTO;
import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;


/**
 * Servlet implementation class UploadServlet
 */
@WebServlet("/upload")
public class UploadServlet extends HttpServlet {
//    private static final long serialVersionUID = 1L;

    // 上传文件存储目录
    private static final String UPLOAD_DIRECTORY = "upload";

    // 上传配置
//    private static final int MEMORY_THRESHOLD   = 1024 * 1024 * 3;  // 3MB
//    private static final int MAX_FILE_SIZE      = 1024 * 1024 * 40; // 40MB
//    private static final int MAX_REQUEST_SIZE   = 1024 * 1024 * 50; // 50MB

    /**
     * 上传数据及保存文件
     */
    protected void doPost(HttpServletRequest request,
                          HttpServletResponse response) throws ServletException, IOException {
        request.setCharacterEncoding("UTF-8");
        response.setCharacterEncoding("UTF-8");
        // 检测是否为多媒体上传
        if (!ServletFileUpload.isMultipartContent(request)) {
            // 如果不是则停止
            PrintWriter writer = response.getWriter();
//            writer.println("Error: 表单必须包含 enctype=multipart/form-data");
//            writer.flush();
            response.getWriter().println(JSONObject.toJSONString(ResultDTO.builder()
                    .code(0)
                    .msg("Error: 表单必须包含 enctype=multipart/form-data")
                    .build()));
            return;
        }

        // 配置上传参数
        DiskFileItemFactory factory = new DiskFileItemFactory();
        // 设置内存临界值 - 超过后将产生临时文件并存储于临时目录中
//        factory.setSizeThreshold(MEMORY_THRESHOLD);
        // 设置临时存储目录
//        factory.setRepository(new File(System.getProperty("java.io.tmpdir")));

//        用于解析前端传递过来的文件
        ServletFileUpload upload = new ServletFileUpload(factory);

        // 设置最大文件上传值
//        upload.setFileSizeMax(MAX_FILE_SIZE);

        // 设置最大请求值 (包含文件和表单数据)
//        upload.setSizeMax(MAX_REQUEST_SIZE);

        // 中文处理
        upload.setHeaderEncoding("UTF-8");

        // 构造临时路径来存储上传的文件
        // 这个路径相对当前应用的目录
        String uploadPath = request.getServletContext().getRealPath("./") + File.separator + UPLOAD_DIRECTORY;


        // 如果目录不存在则创建
        File uploadDir = new File(uploadPath);
        if (!uploadDir.exists()) {
            uploadDir.mkdirs();
        }

        createDir(uploadPath);
        try {
            // 解析请求的内容提取文件数据
            @SuppressWarnings("unchecked")
//                    Integer.parseInt("1")
//                    得到前端传递过来的文件
            List<FileItem> formItems = upload.parseRequest(request);

            if (formItems != null && formItems.size() > 0) {
                // 迭代表单数据
                for (FileItem item : formItems) {
                    // 处理不在表单中的字段
                    if (!item.isFormField()) {
//                        得到文件名称
                        String fileName = new File(item.getName()).getName();
//                        需要将当前的文件名修改，唯一的文件名（同一个文件夹里面不能有相同的文件名）
//                       d:/aa/b/upload/ 16543456787654--a.jpg
                        fileName = System.currentTimeMillis() + "--" + fileName;
                        String filePath = uploadPath + File.separator + fileName;
                        File storeFile = new File(filePath);
                        // 在控制台输出文件的上传路径
                        System.out.println(filePath);
                        // 保存文件到硬盘
                        item.write(storeFile);
//将直接将item的内容保存到web目录
                        {

//                            得到web目录下面的upload地址
                            String path = filePath.split("out")[0] + "/web/" + UPLOAD_DIRECTORY;
//                            创建文件夹
                            createDir(path);
//                            得到web目录下文件的路径
                            File webFile = new File(path, fileName);
//                            将item写道新地址
//                            item可以理解为只能用一次
//                            item.write(webFile);
                            copy(storeFile, webFile);
                        }

//                        返回给前端的路径
                        String path = "/" + UPLOAD_DIRECTORY + "/" + fileName;
                        ImgDTO imgDTO = new ImgDTO(path);
                        ResultDTO resultDTO = ResultDTO.builder()
                                .code(0)
                                .msg("")
                                .data(imgDTO)
                                .build();
                        response.getWriter().println(JSONObject.toJSONString(resultDTO));
                    }

                }
            }
        } catch (Exception ex) {
            ex.printStackTrace();
        }
//        // 跳转到 message.jsp
//        request.getServletContext().getRequestDispatcher("/message.jsp").forward(
//                request, response);
    }

    private void copy(File storeFile, File webFile) {
        try (InputStream inputStream = new FileInputStream(storeFile);
             OutputStream outputStream = new FileOutputStream(webFile)) {
            int read = 0;
            while ((read = inputStream.read()) != -1) {
                outputStream.write(read);
            }
        } catch (Exception e) {

        }
    }

    /**
     * 创建文件夹
     *
     * @param uploadPath
     */
    private void createDir(String uploadPath) {
        File uploadDir = new File(uploadPath);
        if (!uploadDir.exists()) {
            uploadDir.mkdirs();
        }
    }
}